<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--区域数据-->
      <el-col :span="4" :xs="24">
        <div class="box-card">
          <div class="head-container">
            <el-input v-model="filterText" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search"
              style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="regionList" :props="defaultProps" :expand-on-click-node="false"
              :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
              @node-click="handleNodeClick">
              <div class="custom-tree-node" slot-scope="{ node, data }">
                <div>{{ node.label }}</div>
                <div>
                  <i class="el-icon-edit" @click.stop="() => setEditRegion(data)"></i>
                  <i class="el-icon-delete" style="margin-left: 10px;"
                    @click.stop="() => handleDeleteInfoClass(data)"></i>
                </div>
              </div>
            </el-tree>
          </div>
        </div>
      </el-col>


      <el-col :span="20" :xs="24">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="节目名称">
            <el-input v-model="queryParams.programName" placeholder="请输入节目名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="节目状态">
            <el-select v-model="queryParams.programStatus" placeholder="节目状态" clearable>
              <el-option label="审核中" value="0" />
              <el-option label="审核不通过" value="1" />
              <el-option label="审核通过" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:infoClass:add']" type="primary" plain icon="Plus" @click="add">新增分类</el-button>
            <el-button v-hasPermi="['iot:program:add']" type="primary" plain icon="Plus"
              @click="handleAdd">新增节目</el-button>
          </el-col>
          <el-col :span="1.5">
            <!-- <el-button type="info" plain icon="Sort">测试连接</el-button> -->
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>

        <el-table ref="menuTableRef" v-loading="loading" :data="infoList" height="650"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="programName" label="节目名称"></el-table-column>
          <el-table-column prop="programClass" label="节目类型">
            <template #default="scope">
              <el-tag class="ml-2">
                {{ getDeviceClassTypeName(scope.row.programClass) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="programContent" label="节目描述"></el-table-column>
          <el-table-column prop="programStatus" label="节目状态">
            <template #default="scope">
              <el-tag class="ml-2" type="warning" v-if="scope.row.programStatus == '0'">审核中</el-tag>
              <el-tag class="ml-2" type="danger" v-if="scope.row.programStatus == '1'">审核不通过</el-tag>
              <el-tag class="ml-2" type="success" v-if="scope.row.programStatus == '2'">审核通过</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime"> </el-table-column>
          <el-table-column fixed="right" label="操作" width="250">
            <template #default="scope">
              <el-tooltip content="预览" placement="top">
                <el-button v-hasPermi="['iot:program:query']" size="mini" type="text" icon="el-icon-view"
                  @click="viewApp(scope.row)">预览</el-button>
              </el-tooltip>
              <el-tooltip content="修改" placement="top">
                <el-button v-hasPermi="['iot:program:edit']" size="mini" type="text" icon="el-icon-edit"
                  @click="handleUpdate(scope.row)">修改</el-button>
              </el-tooltip>
              <el-tooltip content="下发" placement="top">
                <el-button v-hasPermi="['iot:program:issued']" size="mini" type="text" icon="el-icon-edit-outline"
                  @click="issued(scope.row)">下发</el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button v-hasPermi="['iot:program:remove']" size="mini" type="text" icon="el-icon-delete"
                  @click="handleDelete(scope.row)">删除</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize" @pagination="getList" />

        <Preview :componentData="componentData" :canvasStyleData="canvasStyleData" @close="handlePreviewChange"
          v-if="centerDialogVisible"></Preview>


        <el-dialog title="下发设备" width="30%" :visible.sync="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="下发类型" :label-width="formLabelWidth">
              <el-radio-group v-model="form.type">
                <el-radio label="1">全部设备</el-radio>
                <el-radio label="2">指定设备</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="选择设备" :label-width="formLabelWidth" v-if="form.type == '2'">
              <el-select v-model="form.deviceList" multiple clearable filterable placeholder="请选择设备">
                <el-option v-for="(item, index) in deviceList" :key="index" :label="item.deviceName"
                  :value="item.deviceMac"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="setIssued">确 定</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>


    <el-drawer :title="title" :visible.sync="drawer">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import { programList, programDel, programUpdate, programAdd, programIssued, list } from '@/api/information/index';
import { listinfoClass, addinfoClass, UpdateinfoClass, delInfoClass } from "../../../api/information/infoClass.js"
import Preview from '../../../components/visual-drag/components/Editor/Preview.vue'
export default {
  name: '',
  props: {},
  data() {
    return {
      filterText: '',
      title: "新增分类",
      ruleForm: {
        name: ''
      },
      ruleFormQuery: {
        name: '',
        pageNum: 1,
        pageSize: 10
      },
      rules: {
        name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      drawer: false,
      regionList: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        programName: '',
        programStatus: '',
        programClass: ''
      },
      dialogFormVisible: false,
      form: {
        type: '1',
        deviceList: []
      },
      programObject: {},
      formLabelWidth: '120px',
      loading: false,
      infoList: [],
      showSearch: false,
      centerDialogVisible: false,
      componentData: [],
      canvasStyleData: {},
      queryParamsDevice: {
        pageNum: 1,
        pageSize: 999
      },
      deviceList: [],
      total: 0
    };
  },
  components: { Preview },
  computed: {},
  watch: {
    // 根据名称筛选部门树
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() { },
  mounted() {
    this.getList();
    this.getListInfoClass()
  },
  methods: {
    getDeviceClassTypeName(id) {
      const type = this.regionList.find(item => item.id === id);
      return type ? type.name : '未知类型';
    },
    setEditRegion(data) {
      this.ruleForm = data
      this.drawer = true
      this.title = "修改分类"
    },
    subUpdate() {
      UpdateinfoClass(this.ruleForm).then((res) => {
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.drawer = false
        this.getList()
        this.resetForm()
      });
    },
    handleDeleteInfoClass(val) {
      delInfoClass(val.id).then((res) => {
        this.$message({
          message: '删除成功',
          type: 'success'
        });
        this.getListInfoClass()
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title == "修改分类") {
            this.subUpdate()
          } else {
            this.addinfo()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addinfo() {
      addinfoClass(this.ruleForm).then((res) => {
        this.$message({
          message: '新增成功',
          type: 'success'
        });
        this.drawer = false
        this.getList()
        this.resetForm()
      });
    },
    resetForm(formName) {
      this.ruleForm = {
        name: ''
      }
    },
    add() {
      this.drawer = true
      this.title = "新增分类"
    },
    handleNodeClick(val) {
      console.log(val)
      this.queryParams.programClass = val.id
      this.getList()
    },
    handleQuery() {
      this.getList();
    },
    getListInfoClass() {
      listinfoClass(this.ruleFormQuery).then((res) => {
        this.regionList = res.rows
      });
    },
    // 筛选节点
    filterNode(value, data) {
      console.log(value, data)
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    resetQuery() {
      this.$refs.queryFormRef.resetFields();
      this.handleQuery();
    },
    handleUpdate(row) {
      localStorage.setItem('canvasData', row.programData)
      localStorage.setItem('canvasStyle', row.programStyles)
      this.$router.push({ path: '/Information/editor', query: { id: row.id } })
    },
    /**
     * 获取设备列表
     */
    getDevice() {
      list(this.queryParamsDevice).then((res) => {
        this.deviceList = res.rows
        this.dialogFormVisible = true
      });
    },
    issued(row) {
      this.programObject = row
      this.getDevice();
    },
    setIssued() {
      // console.log(this.form.deviceList)
      // return;
      if (this.programObject.programStatus == '2') {
        programIssued({
          id: this.programObject.id,
          macList: this.form.deviceList,
          type: this.form.type
        }).then((res) => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '下发成功!'
            });
          }
          this.form = {
            type: '1',
            deviceList: []
          }
          this.dialogFormVisible = false
        });
      } else {
        this.$message.error('请通知管理员审核');
      }
    },
    handleDelete(row) {
      this.$confirm(`是否确认删除名称为"${row.programName}"的数据项?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        programDel(row.id).then((res) => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getList();
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getList() {
      programList(this.queryParams).then((res) => {
        this.infoList = res.rows;
        this.total = res.total
      });
    },
    handleAdd() {
      this.$router.push({ path: '/Information/editor' })
    },
    handlePreviewChange() {
      localStorage.removeItem('canvasData')
      localStorage.removeItem('canvasStyle')
      this.$store.commit('setCurComponent', { component: null, index: null })
      this.$store.commit('setComponentData', [])
      this.$store.commit('recordSnapshot')
      this.centerDialogVisible = false
    },
    viewApp(row) {
      this.$store.commit('setComponentData', JSON.parse(row.programData))
      this.$store.commit('setCanvasStyle', JSON.parse(row.programStyles))
      this.centerDialogVisible = true;
    }
  }
};
</script>

<style scoped>
.demo-form-inline {
  padding: 20px;
}

.btn {
  width: 100%;
  text-align: right;
}

.box-card {
  height: 100vh;
  border-right: 1px solid #eee;
  padding: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  padding-right: 8px;
}

.el-tree-node__expand-icon.is-leaf {
  display: none;
}
</style>
